package com.tripwego.client.ui.pageAccueil;

import java.util.List;

import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import com.tripwego.client.event.InitListTripEvent;
import com.tripwego.client.event.InitListTripEventHandler;
import com.tripwego.client.model.TripModel;

public class ListTripWidget extends Composite implements IHomeView, InitListTripEventHandler {

	private Presenter presenter;

	private EventBus eventBus;

	/*
	 * Elements graphiques
	 */
	private VerticalPanel viewPanel = new VerticalPanel();

	// Create a data provider.
	private ListDataProvider<TripModel> dataProvider = new ListDataProvider<TripModel>();
	private List<TripModel> listTrip = null;

	CellTable<TripModel> cellTable = new CellTable<TripModel>();

	TextColumn<TripModel> textColumn = new TextColumn<TripModel>() {
		@Override
		public String getValue(TripModel object) {
			return object.getName();
		}
	};

	private final SingleSelectionModel<TripModel> selectionModel = new SingleSelectionModel<TripModel>();

	/**
	 * 
	 */
	public ListTripWidget() {
		super();

		viewPanel.setStylePrimaryName("CRWidget");

		// dataProvider.addDataDisplay(cellTable);
		dataProvider.addDataDisplay(cellTable);

		viewPanel.add(cellTable);

		cellTable.addColumn(textColumn, "Derniers Trips ajout\u00E9s");
		cellTable.setSelectionModel(selectionModel);

		selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
			public void onSelectionChange(SelectionChangeEvent event) {

				TripModel selected = selectionModel.getSelectedObject();

				if (selected != null && selected.getId() != null) {
					History.newItem("mytrip:".concat(selected.getId().toString()));
				}
			}
		});

		init();
	}

	@Override
	public Widget asWidget() {
		return viewPanel;
	}

	@Override
	public void setPresenter(Presenter presenter) {
		this.presenter = presenter;
	}

	@Override
	public void setEventBus(EventBus eventBus) {
		this.eventBus = eventBus;

		// ecouteurs d'evenements
		eventBus.addHandler(InitListTripEvent.TYPE, this);
	}

	@Override
	public void init() {
	}

	@Override
	public void handleInitListTripEvent(InitListTripEvent event) {
		listTrip = dataProvider.getList();

		listTrip.clear();

		for (TripModel tripModel : event.getResults()) {
			listTrip.add(tripModel);
		}

		dataProvider.refresh();
	}
}
